<?php

namespace addons\qingdong\controller;

use addons\qingdong\model\AchievementRecords;
use addons\qingdong\model\AttendanceStatisc;
use addons\qingdong\model\Business;
use addons\qingdong\model\BusinessStatus;
use addons\qingdong\model\Flow;
use addons\qingdong\model\FormApproval;
use addons\qingdong\model\Message;
use addons\qingdong\model\Contract;
use addons\qingdong\model\Consume;
use addons\qingdong\model\Staff;
use addons\qingdong\model\Receivables;
use addons\qingdong\model\Achievement;
use addons\qingdong\model\Approval;
use addons\qingdong\model\ExamineRecord as ExamineRecordModel;
use think\Cache;
use think\Db;
use think\Exception;
use think\Log;

/**
 * 审批记录
 */
class ExamineRecord extends StaffApi {
	protected $noNeedLogin = [];
	protected $noNeedRight = [];


	//审批记录
	public function getList() {
		$relation_type = input('relation_type');
		$relation_id   = input('relation_id');

		$list = ExamineRecordModel::where([
			'relation_type' => $relation_type,
			'relation_id'   => $relation_id
		])->with('checkStaff')->select();
		$this->success('请求成功', $list);
	}


	//审核
	public function examine() {
		$relation_type = input('relation_type');
		$relation_id   = input('relation_id');
		$content       = input('content');
		$status        = input('status');
        $record = ExamineRecordModel::where([
            'relation_type' => $relation_type,
            'relation_id' => $relation_id,
            'status' => 0,
            'check_staff_id' => $this->auth->id
        ])->find();
		if (empty($record)) {
			$this->error('没有待审核数据');
		}
		$staff = Staff::info();
		Db::startTrans();
		try {
			$model = new ExamineRecordModel();
			if ($model->isUpdate(true)->save([
					'status'     => $status,
					'content'    => $content,
					'check_time' => time()
				], ['id' => $record['id']]) == false) {
				throw new Exception('修改失败');
			}
			switch ($relation_type) {
				case $model::CONSUME_TYPE://费用
					$rowModel = new \addons\qingdong\model\Consume();
					$row      = $rowModel->where(['id' => $relation_id])->find();
				break;
				case $model::CONTRACT_TYPE://合同
					$rowModel = new \addons\qingdong\model\Contract();
					$row      = $rowModel->where(['id' => $relation_id])->find();
				break;
				case $model::RECEIVABLES_TYPE://回款
					$rowModel = new \addons\qingdong\model\Receivables();
					$row      = $rowModel->where(['id' => $relation_id])->find();
				break;
				case $model::ACHIEVEMENT_TYPE://业绩目标
					$rowModel = new \addons\qingdong\model\AchievementRecords();
					$row      = $rowModel->where(['id' => $relation_id])->find()->toArray();
				break;
                case $model::APPROVAL_TYPE://审批
                    $rowModel = new \addons\qingdong\model\Approval();
                    $row = $rowModel->where(['id' => $relation_id])->find()->toArray();
                    $row['staff_id'] = $row['create_staff_id'];
                    break;
                case $model::CARD_TYPE://补卡审核
                    $rowModel = new \addons\qingdong\model\AttendanceCard();
                    $row = $rowModel->where(['id' => $relation_id])->find()->toArray();
                    $row['staff_id'] = $row['create_staff_id'];
                    break;
                case $model::LEAVE_TYPE://请假
                    $rowModel = new \addons\qingdong\model\Leave();
                    $row = $rowModel->where(['id' => $relation_id])->find()->toArray();
                    $row['staff_id'] = $row['create_staff_id'];
                    break;
				default:
					throw new Exception('参数错误');
			}
			if ($message = Message::where(['relation_type' => 'examine', 'relation_id' => $record['id'],'to_staff_id'=>$this->auth->id])->find()) {
			    Message::where(['id' => $message['id']])->update(['status' => 1, 'read_time' => time()]);
			}
			$check_staff_ids   = explode(',', trim($row['check_staff_ids'], ','));
			$check_staff_ids[] = $staff->id;
			if ($status == 1) {//审核通过
               $flow= Flow::getstepdetail($relation_type,$relation_id);
                //给下一审核人发送通知
                $result=Flow::sendStepRecord($flow,$relation_type, $relation_id,$check_staff_ids,$staff->id);

				//已完成审核
				if ($result['status']== true) {
					$rowModel->save([
						'check_status'   => 2,
						'check_staff_ids' => implode(',', $check_staff_ids),
                        'order_id'=>$result['order_id']
					], ['id' => $relation_id]);
					switch ($relation_type) {
						case $model::CONTRACT_TYPE://合同
							\addons\qingdong\model\Customer::where(['id'=>$row['customer_id']])->update(['contract_status'=>1]);
                            //合同签署成功后商机变为赢单
                            if($row['business_id']){
                                BusinessStatus::create(array('business_id'=>$row['business_id'],'type'=>4,'remark'=>'合同签署'));
                                Business::where(array('id'=>$row['business_id']))->update(array('contract_status'=>1,'updatetime'=>time()));
                            }
							break;
						case $model::ACHIEVEMENT_TYPE://业绩目标
							$m=new \addons\qingdong\model\Achievement();
							$m->where(['type'=>$row['type'],'status'=>$row['status'],'obj_id'=>$row['obj_id']])->delete();
							unset($row['id']);
                            unset($row['createtime']);
                            unset($row['updatetime']);
                            unset($row['deletetime']);
                            $m->allowField(true)->save($row);
							$row['staff_id']=$row['obj_id'];
						break;
						case $model::RECEIVABLES_TYPE://回款
							$m=new \addons\qingdong\model\Contract();
                            $contract=$m->where(['id'=>$row['contract_id']])->with(['receivables'])->find();
                            if($contract['receivables']['repayment_money'] >= $contract['money']){
                                $m->save(['contract_status'=>1],['id'=>$row['contract_id']]);//已完成
                            }
						break;
						case $model::CARD_TYPE://补卡
                            if($row['type'] == 1){//早退
                                $name='clock_out_status';
                                $name_time='clock_out';
                            }else{//迟到
                                $name='clock_in_status';
                                $name_time='clock_in';
                            }
                            AttendanceStatisc::where(['id'=>$row['statisc_id']])->update([$name=>5,$name_time=>$row['time']]);
						break;
						case $model::LEAVE_TYPE://请假
						break;
					}

					Message::addMessage(Message::EXAMINE_ADOPT_TYPE,$record['id'],$row['owner_staff_id']?? $row['staff_id'],$staff->id);

                    //删除 或签的待审批通知
                    Message::setRead(Message::EXAMINE_TYPE,$record['id']);
                    ExamineRecordModel::where([
                        'relation_type' => $relation_type,
                        'relation_id' => $relation_id,
                        'status' => 0,
                    ])->update(['status'=>3]);
				} else {
					$rowModel->save([
                        'check_staff_ids' => implode(',', $check_staff_ids),
                        'order_id'=>$result['order_id']
                    ], ['id' => $relation_id]);
				}
			} else {
				//审核未通过
				$rowModel->save(['check_status' => 3, 'check_staff_ids' => ''], ['id' => $relation_id]);
				Message::addMessage(Message::EXAMINE_REFUSE_TYPE,$record['id'],$row['owner_staff_id']?? $row['staff_id'],$staff->id,'');

                //删除待审批通知
                $ids = ExamineRecordModel::where([
                    'relation_type' => $relation_type,
                    'relation_id' => $relation_id,
                    'status' => 0,
                ])->column('id');
                Message::where(['relation_type' => Message::EXAMINE_TYPE, 'relation_id' => ['in', $ids], 'status' => 0])->update(['read_time' => time(), 'status' => 1]);

                ExamineRecordModel::where([
                    'relation_type' => $relation_type,
                    'relation_id' => $relation_id,
                    'status' => 0,
                ])->update(['status'=>3]);
			}


			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
            Log::record($e->getMessage());
			$this->error($e->getMessage());
		}


		$this->success('审核成功');
	}

    /**
     * 获取审批列表
     */
    public function get_examine_list()
    {
        $limit = input("limit/d", 10);
        //合同审批，回款审批、业绩目标审批、办公审批 费用
        $relation_type = input('type');
        $status =  input('status',0);
        if($status == 1){
            $status = array('in','1,2');
        }
        $data = ExamineRecordModel::where(['relation_type' => $relation_type,
            'status' => $status,
            'check_staff_id' => $this->auth->id])->order('id desc')->paginate($limit)->toArray();
        if($data['data']){
            foreach($data['data'] as $k=>$v){
                $data['data'][$k]['content_info'] = Message::where(array('relation_id'=>$v['id'],'relation_type'=>'examine'))->value('content');
                if ($v['relation_type'] == ExamineRecordModel::CONSUME_TYPE) {
                    $data['data'][$k]['relation_name'] = Consume::where(['id' => $v['relation_id']])->value('consume_type');
                } elseif ($v['relation_type'] == ExamineRecordModel::CONTRACT_TYPE) {
                    $data['data'][$k]['relation_name'] = Contract::where(['id' => $v['relation_id']])->value('name');
                } elseif ($v['relation_type'] == ExamineRecordModel::RECEIVABLES_TYPE) {
                    $data['data'][$k]['relation_name'] = Receivables::where(['id' => $v['relation_id']])->value('number');
                } elseif($v['relation_type'] == ExamineRecordModel::ACHIEVEMENT_TYPE) {
                    $data['data'][$k]['relation_name'] = $acchieve = AchievementRecords::where(['id' => $v['relation_id']])->value('year');;
                } elseif($v['relation_type'] == ExamineRecordModel::APPROVAL_TYPE) {
                    $approval = Approval::where(['id' => $v['relation_id']])->value('formapproval_id');
                    $data['data'][$k]['relation_name'] = '';
                    if($approval){
                        $data['data'][$k]['relation_name'] = FormApproval::where(['id'=>$approval])->value('name');
                    }

                }elseif($v['relation_type'] == ExamineRecordModel::CARD_TYPE) {
                    $data['data'][$k]['relation_name'] = '补卡';
                }elseif($v['relation_type'] == ExamineRecordModel::LEAVE_TYPE) {
                    $data['data'][$k]['relation_name'] = '请假';
                }
                else{
                    $data['data'][$k]['relation_name']='';
                }
            }
        }


        $this->success('请求成功', $data);
    }
}
